<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ETF行业配置分析</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/4.6.0/js/bootstrap.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background-color: #f5f7fa;
        }
        .container {
            max-width: 1400px;
        }
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #409eff;
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 12px 20px;
            font-size: 16px;
            font-weight: 500;
        }
        .card-body {
            padding: 20px;
        }
        .chart-container {
            height: 400px;
            margin-bottom: 20px;
        }
        .btn-primary {
            background-color: #409eff;
            border-color: #409eff;
        }
        .btn-primary:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
        }
        .btn-danger {
            background-color: #f56c6c;
            border-color: #f56c6c;
        }
        .btn-danger:hover {
            background-color: #f78989;
            border-color: #f78989;
        }
        .btn-success {
            background-color: #67c23a;
            border-color: #67c23a;
        }
        .btn-success:hover {
            background-color: #85ce61;
            border-color: #85ce61;
        }
        .btn-group {
            margin-bottom: 15px;
        }
        .table {
            background-color: white;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        .table thead th {
            background-color: #f5f7fa;
            font-weight: 600;
            color: #606266;
            border-bottom: 1px solid #ebeef5;
        }
        .table tbody tr:hover {
            background-color: #fafafa;
        }
        .form-control {
            border-radius: 4px;
            border: 1px solid #dcdfe6;
        }
        .form-control:focus {
            border-color: #409eff;
            outline: none;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #909399;
        }
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .stats-card .number {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .stats-card .label {
            font-size: 14px;
            opacity: 0.9;
        }
        .alert {
            margin-top: 15px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h2 class="text-center mb-5">ETF行业配置分析</h2>
        
        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="number" id="totalBlocks">0</div>
                    <div class="label">板块总数</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                    <div class="number" id="dateCount">0</div>
                    <div class="label">报告日期数</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                    <div class="number" id="maxRatio">0.00%</div>
                    <div class="label">最大配置比例</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                    <div class="number" id="avgRatio">0.00%</div>
                    <div class="label">平均配置比例</div>
                </div>
            </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-cogs mr-2"></i>数据操作
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="btn-group">
                            <button id="fetchBtn" class="btn btn-primary">
                                <i class="fa fa-refresh mr-1"></i>抓取数据
                            </button>
                            <button id="calculateBtn" class="btn btn-success">
                                <i class="fa fa-calculator mr-1"></i>计算配置比例
                            </button>
                            <button id="deleteOldBtn" class="btn btn-danger">
                                <i class="fa fa-trash mr-1"></i>删除旧数据
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-inline float-right">
                            <label for="reportDate" class="mr-2">报告日期：</label>
                            <input type="date" id="reportDate" class="form-control mr-2">
                            <button id="queryByDateBtn" class="btn btn-primary">
                                <i class="fa fa-search mr-1"></i>查询
                            </button>
                        </div>
                    </div>
                </div>
                <div id="message" class="alert" style="display: none;"></div>
            </div>
        </div>
        
        <!-- 图表展示 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-pie-chart mr-2"></i>行业配置比例分布
            </div>
            <div class="card-body">
                <div id="pieChart" class="chart-container"></div>
            </div>
        </div>
        
        <!-- 柱状图 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-bar-chart mr-2"></i>行业配置比例排序
            </div>
            <div class="card-body">
                <div id="barChart" class="chart-container"></div>
            </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="card">
            <div class="card-header">
                <i class="fa fa-table mr-2"></i>ETF行业配置数据列表
            </div>
            <div class="card-body">
                <div id="dataTableContainer">
                    <div class="loading">
                        <i class="fa fa-spinner fa-spin fa-2x mr-2"></i>
                        <span>加载中...</span>
                    </div>
                    <table class="table table-striped table-hover" id="dataTable" style="display: none;">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>板块代码</th>
                                <th>板块占比(%)</th>
                                <th>报告日期</th>
                                <th>更新时间</th>
                            </tr>
                        </thead>
                        <tbody id="tableBody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 设置默认日期为今天
            const today = new Date().toISOString().split('T')[0];
            $('#reportDate').val(today);
            
            // 初始化图表
            const pieChart = echarts.init(document.getElementById('pieChart'));
            const barChart = echarts.init(document.getElementById('barChart'));
            
            // 加载数据
            loadAllData();
            
            // 抓取数据按钮点击事件
            $('#fetchBtn').click(function() {
                $(this).attr('disabled', true);
                showMessage('info', '正在抓取数据，请稍候...');
                
                $.ajax({
                    url: '/etfblock/fetch',
                    type: 'GET',
                    success: function(result) {
                        if (result.success) {
                            showMessage('success', result.message);
                            loadAllData();
                        } else {
                            showMessage('error', result.message);
                        }
                    },
                    error: function() {
                        showMessage('error', '请求失败，请检查网络连接');
                    },
                    complete: function() {
                        $('#fetchBtn').attr('disabled', false);
                    }
                });
            });
            
            // 计算配置比例按钮点击事件
            $('#calculateBtn').click(function() {
                const reportDate = $('#reportDate').val();
                if (!reportDate) {
                    showMessage('warning', '请选择报告日期');
                    return;
                }
                
                $(this).attr('disabled', true);
                showMessage('info', '正在计算配置比例，请稍候...');
                
                $.ajax({
                    url: '/etfblock/calculate?reportDate=' + reportDate,
                    type: 'GET',
                    success: function(result) {
                        if (result.success) {
                            showMessage('success', result.message);
                            queryByDate();
                        } else {
                            showMessage('error', result.message);
                        }
                    },
                    error: function() {
                        showMessage('error', '请求失败，请检查网络连接');
                    },
                    complete: function() {
                        $('#calculateBtn').attr('disabled', false);
                    }
                });
            });
            
            // 删除旧数据按钮点击事件
            $('#deleteOldBtn').click(function() {
                if (confirm('确定要删除2年前的旧数据吗？')) {
                    $(this).attr('disabled', true);
                    showMessage('info', '正在删除旧数据，请稍候...');
                    
                    $.ajax({
                        url: '/etfblock/deleteOld?days=730',
                        type: 'GET',
                        success: function(result) {
                            if (result.success) {
                                showMessage('success', result.message);
                                loadAllData();
                            } else {
                                showMessage('error', result.message);
                            }
                        },
                        error: function() {
                            showMessage('error', '请求失败，请检查网络连接');
                        },
                        complete: function() {
                            $('#deleteOldBtn').attr('disabled', false);
                        }
                    });
                }
            });
            
            // 按日期查询按钮点击事件
            $('#queryByDateBtn').click(queryByDate);
            
            // 加载所有数据
            function loadAllData() {
                $.ajax({
                    url: '/etfblock/listAll',
                    type: 'GET',
                    success: function(data) {
                        updateTable(data);
                        updateCharts(data);
                        updateStats(data);
                    },
                    error: function() {
                        showMessage('error', '加载数据失败');
                    }
                });
            }
            
            // 按日期查询
            function queryByDate() {
                const reportDate = $('#reportDate').val();
                if (!reportDate) {
                    showMessage('warning', '请选择报告日期');
                    return;
                }
                
                $.ajax({
                    url: '/etfblock/listByDate?reportDate=' + reportDate,
                    type: 'GET',
                    success: function(data) {
                        updateTable(data);
                        updateCharts(data);
                        updateStats(data);
                    },
                    error: function() {
                        showMessage('error', '查询失败');
                    }
                });
            }
            
            // 更新表格
            function updateTable(data) {
                const tbody = $('#tableBody');
                tbody.empty();
                
                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        const row = $('<tr>');
                        row.append($('<td>').text(item.id));
                        row.append($('<td>').text(item.blockCode));
                        row.append($('<td>').text((item.blockRatio || 0).toFixed(2) + '%'));
                        row.append($('<td>').text(formatDate(item.reportDate)));
                        row.append($('<td>').text(formatDateTime(item.updateTime)));
                        tbody.append(row);
                    });
                    $('#dataTable').show();
                    $('.loading').hide();
                } else {
                    $('.loading').html('<i class="fa fa-info-circle mr-2"></i><span>暂无数据</span>');
                    $('#dataTable').hide();
                }
            }
            
            // 更新图表
            function updateCharts(data) {
                if (!data || data.length === 0) {
                    pieChart.setOption({series: [{data: []}]});
                    barChart.setOption({series: [{data: []}]});
                    return;
                }
                
                // 准备图表数据
                const chartData = data.map(item => ({
                    name: item.blockCode,
                    value: item.blockRatio
                }));
                
                // 更新饼图
                pieChart.setOption({
                    tooltip: {
                        trigger: 'item',
                        formatter: '{b}: {c}% ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [{
                        name: '板块配置',
                        type: 'pie',
                        radius: '50%',
                        data: chartData,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }]
                });
                
                // 更新柱状图
                barChart.setOption({
                    tooltip: {
                        trigger: 'axis',
                        formatter: '{b}: {c}%'
                    },
                    xAxis: {
                        type: 'category',
                        data: data.map(item => item.blockCode)
                    },
                    yAxis: {
                        type: 'value',
                        name: '占比(%)'
                    },
                    series: [{
                        name: '板块配置比例',
                        type: 'bar',
                        data: data.map(item => item.blockRatio),
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {offset: 0, color: '#83bff6'},
                                {offset: 0.5, color: '#188df0'},
                                {offset: 1, color: '#188df0'}
                            ])
                        }
                    }]
                });
            }
            
            // 更新统计信息
            function updateStats(data) {
                if (!data || data.length === 0) {
                    $('#totalBlocks').text('0');
                    $('#dateCount').text('0');
                    $('#maxRatio').text('0.00%');
                    $('#avgRatio').text('0.00%');
                    return;
                }
                
                // 计算统计数据
                const blockCount = new Set(data.map(item => item.blockCode)).size;
                const dateCount = new Set(data.map(item => formatDate(item.reportDate))).size;
                const ratios = data.map(item => item.blockRatio || 0);
                const maxRatio = Math.max(...ratios);
                const avgRatio = ratios.reduce((sum, ratio) => sum + ratio, 0) / ratios.length;
                
                // 更新统计卡片
                $('#totalBlocks').text(blockCount);
                $('#dateCount').text(dateCount);
                $('#maxRatio').text(maxRatio.toFixed(2) + '%');
                $('#avgRatio').text(avgRatio.toFixed(2) + '%');
            }
            
            // 显示消息
            function showMessage(type, message) {
                const messageBox = $('#message');
                messageBox.removeClass('alert-info alert-success alert-warning alert-danger');
                messageBox.addClass('alert-' + type);
                messageBox.text(message);
                messageBox.show();
                
                // 3秒后自动隐藏
                setTimeout(() => {
                    messageBox.fadeOut();
                }, 3000);
            }
            
            // 格式化日期
            function formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.getFullYear() + '-' + 
                       (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                       date.getDate().toString().padStart(2, '0');
            }
            
            // 格式化日期时间
            function formatDateTime(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return formatDate(date) + ' ' + 
                       date.getHours().toString().padStart(2, '0') + ':' + 
                       date.getMinutes().toString().padStart(2, '0') + ':' + 
                       date.getSeconds().toString().padStart(2, '0');
            }
            
            // 响应式处理
            window.addEventListener('resize', function() {
                pieChart.resize();
                barChart.resize();
            });
        });
    </script>
</body>
</html>